package com.xx.dk.tbsalling.aismessages.ais.messages.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xx.dk.tbsalling.aismessages.ais.messages.AISMessage;
import com.xx.dk.tbsalling.aismessages.ais.messages.ClassBCSStaticDataReport;
import com.xx.domain.ShipBaseInfo;
import com.xx.netty.server.constants.AisConstants;
import com.xx.utils.redis.RedisUtil;
import com.xx.web.domain.entity.ZlShip;
import com.xx.web.mapper.ZlShipMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @description: 24 静态数据报告
 * @author: xx
 * @Date 2023/7/14 17:50
 * @version: 1.0
 */
@Component
@RequiredArgsConstructor
public class ClassBCSStaticDataReportHandler implements AISMessageHandler {

    private final RedisUtil redisUtil;
    private final ZlShipMapper shipMapper;

    @Override
    public void handle(AISMessage message) {
        ClassBCSStaticDataReport data = (ClassBCSStaticDataReport) message;
        //System.out.println(data.getMessageType().getCode() +"-----" + data.toString());
        Integer mmsi = data.getSourceMmsi().getMMSI();
        ShipBaseInfo info = redisUtil.get(AisConstants.AIS_SHIP_INFO + mmsi);
        //if (!redisUtil.exists(AisConstants.AIS_SHIP_INFO + mmsi)) { //baseInfo is null,so new and assemble the data
        if (info != null) {
            if (StringUtils.isBlank(info.getName())) {
                if (data.getPartNumber() == 0) {
                    info.setName(data.getShipName());
                    //cached redis
                    redisUtil.set(AisConstants.AIS_SHIP_INFO + mmsi, info, 86400 * 3L);
                }
            }
        } else {
            ShipBaseInfo baseInfo = new ShipBaseInfo(data);
            //if (StringUtils.isNotBlank(baseInfo.getName())) {
            ZlShip zlShip =
                    shipMapper.selectOne(Wrappers.<ZlShip>lambdaQuery().select(ZlShip::getLocalName,
                            ZlShip::getFlagCode).eq(StringUtils.isNotBlank(baseInfo.getName()), ZlShip::getShipNameEn
                            , baseInfo.getName()).or().eq(ZlShip::getMmsi, mmsi).last("limit 1"));
            baseInfo.setZlShip(zlShip);
            //}
            //cached redis
            redisUtil.set(AisConstants.AIS_SHIP_INFO + mmsi, baseInfo, 86400 * 3L);
        }
    }
}
